package cn.itcast.demo.mq.work;

import cn.itcast.demo.mq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 虎哥
 */
public class ReceiveDemo2 {
    public static final String QUEUE_NAME = "work.queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 建立连接
        Connection connection = ConnectionUtils.getConnection();
        // 获取通道Channel
        Channel channel = connection.createChannel();
        // 创建队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 配置，每次只能投递一个消息
        channel.basicQos(1);
        // 创建一个Consumer消费者
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 获取消息体
                String msg = new String(body);
                // 处理消息
                System.out.println("消费者2：" + msg);
                // 消息的手动确认
                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };

        // 消费消息，指定消息队列、消费消息的回调函数
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}
